<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名称" prop="classificationName">
        <el-input v-model="queryParams.classificationName" placeholder="请输入分类名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="是否删除" prop="delFlag">
        <el-select v-model="queryParams.delFlag" placeholder="" clearable>
          <el-option v-for="(item,index) in data_del" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="备注" prop="remark">
        <el-input v-model="queryParams.remark" placeholder="请输入备注" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['dataClassification:dataClassification:add']">新增</el-button>
        <!-- <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['dataClassification:dataClassification:add']">新增</el-button> -->
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['dataClassification:dataClassification:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['dataClassification:dataClassification:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['dataClassification:dataClassification:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataClassificationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分类名称" align="center" prop="classificationName" />
      <el-table-column label="表头" align="center" prop="tableHead" show-overflow-tooltip />
      <el-table-column label="共享状态" align="center" prop="classificationType">
        <template #default="scope">
          <dict-tag :options="data_share" :value="scope.row.classificationType" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="删除标志" align="center" prop="delFlag">
        <template #default="scope">
          <dict-tag :options="data_del" :value="scope.row.delFlag" />
        </template>
      </el-table-column> -->
      <el-table-column label="创建人" align="center" prop="createBy" />
      <!-- <el-table-column label="共享用户" align="center" prop="createBy" show-overflow-tooltip>
        <template #default="scope">
          <span v-for="(item,index) in scope.row.dataClassificationUserList">{{item.userName}}{{index ==
            scope.row.dataClassificationUserList.length -1 ? '' : ','}}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['dataClassification:dataClassification:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['dataClassification:dataClassification:remove']">删除</el-button>
          <!-- <el-button link type="primary" icon="Delete" @click="sureHandleDelete(scope.row)"
            v-hasPermi="['dataClassification:dataClassification:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改分类管理对话框 -->
    <el-dialog :title="title" v-model="open" width="20%">
      <el-form ref="dataClassificationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="classificationName">
          <el-input v-model="form.classificationName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <!-- <el-form-item label="共享状态" prop="classificationType">
          <el-select v-model="form.classificationType" placeholder="请选择是否共享">
            <el-option v-for="dict in data_share" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item v-for="(item,index) in form.dataColumn" :key="index" :label="'字段'+ (Number(index) + 1)"
          :prop="`dataColumn.${index}.dataValue`" :rules="rules.dataValue">
          <div style="display: flex;align-items: center;width: 100%;">
            <el-input v-model="item.dataValue" placeholder="请输入备注" style="flex: 1;width: 100%;" />
            <div style="margin-left: 20px;">
              <el-switch v-model="item.dataType" />
            </div>
            <el-icon v-if="index == 0 && form.dataColumn.length < 20"
              style="font-size: 30px;color: #409EFF;margin-left: 20px;cursor: pointer;" @click="addDataColum">
              <CirclePlus />
            </el-icon>
            <el-icon v-else style="font-size: 30px;color: red;margin-left: 20px;cursor: pointer;"
              @click="closeDataColum(index)">
              <CircleClose />
            </el-icon>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="DataClassification">
  import { listDataClassification, getDataClassification, delDataClassification, addDataClassification, updateDataClassification } from "@/api/dataClassification/dataClassification"

  const { proxy } = getCurrentInstance()
  const { data_share, data_del } = proxy.useDict('data_share', 'data_del')
  const dataClassificationList = ref([])
  const open = ref(false)
  const buttonLoading = ref(false)
  const loading = ref(true)
  const showSearch = ref(true)
  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const total = ref(0)
  const title = ref("")
  const validateDataValue = (rule, value, callback) => {
    console.log(value, 'ABCDEFG-validateDataColumn')
  }
  const data = reactive({
    form: {
      dataColumn: [
        {
          dataName: 'data1', // 表头字段
          dataValue: '', // 表头名字
          dataType: 0, // 0 不展示 展示
        },
      ],
      classificationType: '0'
    },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      classificationId: undefined,
      classificationName: undefined,
      tableHead: undefined,
      userId: undefined,
      classificationType: undefined,
      delFlag: '0',
      remark: undefined,
      createBy: undefined,
      createTime: undefined,
      updateBy: undefined,
      updateTime: undefined
    },
    rules: {
      classificationName: [
        { required: true, message: "分类名称不能为空", trigger: "blur" }
      ],
      dataValue: [
        { required: true, message: '表头名不能为空哦', trigger: 'blur' }
      ],
    }
  })
  const { queryParams, form, rules } = toRefs(data)


  /** 查询分类管理列表 */
  function getList() {
    loading.value = true
    listDataClassification(queryParams.value).then(response => {
      dataClassificationList.value = response.rows
      total.value = response.total
      loading.value = false
    })
  }

  // 取消按钮
  function cancel() {
    open.value = false
    reset()
  }

  // 表单重置
  function reset() {
    form.value = {
      classificationId: null,
      classificationName: null,
      classificationType: '0',
      tableHead: null,
      userId: null,
      dataColumn: [
        {
          // dataName: 'data1', // 表头字段
          dataValue: '', // 表头名字
          dataType: 0, // 0 不展示 展示
        },
      ],
      delFlag: '0',
      remark: null,
      createBy: null,
      createTime: null,
      updateBy: null,
      updateTime: null
    }
    proxy.resetForm("dataClassificationRef")
  }
  function closeDataColum(index) {
    form.value.dataColumn.splice(index, 1)
  }
  //
  function addDataColum(index) {
    form.value.dataColumn.push(
      {
        // dataName: 'data' + (form.value.dataColumn.length + 1), // 表头字段
        dataValue: '', // 表头名字
        dataType: 0, // 0 不展示 展示
      }
    )
    console.log(form.value.dataColumn, 'ABCDEFG-addDataColum')
  }
  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef")
    handleQuery()
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.classificationId)
    single.value = selection.length != 1
    multiple.value = !selection.length
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset()
    open.value = true
    title.value = "添加分类管理"
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    loading.value = true
    reset()
    const _classificationId = row.classificationId || ids.value
    getDataClassification(_classificationId).then(response => {
      loading.value = false
      let tableHead = response.data && response.data.tableHead ? JSON.parse(response.data.tableHead) : []
      if (tableHead.length > 0) {
        tableHead.forEach((item) => {
          item.dataType = item.dataType == 1 ? true : false
        })
      }
      form.value = response.data
      open.value = true
      title.value = "修改分类管理"
      form.value.dataColumn = tableHead.length > 0 ? tableHead : [
        {
          // dataName: 'data1', // 表头字段
          dataValue: '', // 表头名字
          dataType: 0, // 0 不展示 展示
        },
      ]
    })
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["dataClassificationRef"].validate(valid => {
      if (valid) {
        let dataColumn = JSON.parse(JSON.stringify(form.value.dataColumn))
        dataColumn.forEach((item, index) => {
          item.dataName = 'data' + (index + 1)
          item.dataType = item.dataType == true ? 1 : 0
        })
        // console.log(dataColumn, 'ABCDEFG-submitForm');
        // console.log(JSON.stringify(dataColumn), 'ABCDEFG-submitForm');
        form.value.tableHead = JSON.stringify(dataColumn)
        buttonLoading.value = true
        if (form.value.classificationId != null) {
          updateDataClassification(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          }).finally(() => {
            buttonLoading.value = false
          })
        } else {
          addDataClassification(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          }).finally(() => {
            buttonLoading.value = false
          })
        }
      }
    })
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _classificationIds = row.classificationId || ids.value
    proxy.$modal.confirm('是否确分类管理编号为"' + _classificationIds + '"的数据项放入回收站？').then(function () {
      loading.value = true
      return delDataClassification(_classificationIds)
    }).then(() => {
      loading.value = true
      getList()
      proxy.$modal.msgSuccess("删除成功")
    }).catch(() => {
    }).finally(() => {
      loading.value = false
    })
  }
  // const sureHandleDelete = (row) => {
  //   const _classificationIds = row.classificationId || ids.value
  //   proxy.$modal.confirm('是否确认删除分类管理编号为"' + _classificationIds + '"的数据项？').then(function () {
  //     loading.value = true
  //     return sureDelDataClassification(_classificationIds)
  //   }).then(() => {
  //     loading.value = true
  //     getList()
  //     proxy.$modal.msgSuccess("删除成功")
  //   }).catch(() => {
  //   }).finally(() => {
  //     loading.value = false
  //   })
  // }
  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('dataClassification/dataClassification/export', {
      ...queryParams.value
    }, `dataClassification_${new Date().getTime()}.xlsx`)
  }
  getList();
</script>
<style lang="scss" scoped>
  .el-row {
    display: flex;
    /* align-items: center; */
    flex-wrap: wrap;
  }

  .demo-ruleForm {
    width: 100%;

    :deep() {
      .el-input:not(.el-message-box__input .el-input) {
        max-width: 100% !important;
      }

      .el-select {
        width: 100% !important;
      }

      .el-input {
        width: 100% !important;
      }

      .el-date-editor--daterange.el-input,
      .el-date-editor--daterange.el-input__inner,
      .el-date-editor--timerange.el-input,
      .el-date-editor--timerange.el-input__inner {
        width: 100% !important;
        flex: 1 !important;
      }
    }
  }

  :deep() {
    .el-dialog {
      display: flex;
      flex-direction: column;
      margin: 0 !important;
      position: absolute;
      top: 40%;
      left: 50%;
      transform: translate(-50%, -40%);
      max-height: calc(100% - 60px);
      max-width: calc(100% - 30px);
    }

    .el-dialog .el-dialog__body {
      flex: 1;
      overflow: auto;
    }
  }
</style>
